<template>
  <view class="root">
    <view class="content">
      <yy-scroll-view :static-params="staticParams" ref="scrllViewRef" request-url="/mini/wb/deviceinfo/pickup"
        :auto-request="false" :request-callback="handleCallBack">
        <template slot-scope="data">
          <view class="care-item" v-for="(item, index) in data.list" :key="index">
            <view class="item-box">
              <view class="box-left">
                <view class="item-title">
                  录音片段
                </view>
                <view class="item-i">
                  <view class="item-label">
                    录音时间:
                  </view>
                  <view class="item-value">
                    {{item.eventTime}}
                  </view>
                </view>
              </view>
              <image class="s-img" :src="baseimgUrl + 'start-sound.png'" @click="handlePlay(item, data.list, index)"
                v-if="data.list[index].play == false">
              </image>
              <image v-else class="s-img" :src="baseimgUrl + 'pause.png'" @click="handlePause(item, data.list, index)">
              </image>
            </view>
          </view>
        </template>
      </yy-scroll-view>
    </view>
    <view class="bottom">
      <u-button text="获取远程拾音片段" :custom-style="halfColorButton" @click="handleAddVoive"></u-button>
    </view>

    <u-modal @cancel="show = false" @confirm="handleStartVoice" showCancelButton :show="show" title="提示"
      content='此功能是为了确认患者安全，严禁用于违法用途！是否要获取设备周边环境音？'></u-modal>


    <u-modal :show="showVoice" :showConfirmButton="false" :content='content'>
      <view class="voice-box">
        <image :src="baseimgUrl + 'recording-icon.gif'" class="vioce-img"></image>
        <view class="tt-1">正在远程拾音中</view>
        <view class="tt-2">(系统默认拾取15秒环境音)</view>
        <view class="tt-3">倒计时{{countdown}}s</view>
      </view>
    </u-modal>
    <yy-watermark></yy-watermark>
  </view>
</template>

<script>
  import {
    navTo,
    halfColorButton,
    getOptionsParams,
    isLoading,
    Toast,
    getRequestBaseUrl,
    parseJson
  } from '@/utils/util.js'
  import moment from '@/utils/moment'
  import {
    getAction
  } from '../utils/request'
  import WebsocketTask from '@/utils/websocket.js'




  export default {
    data() {
      return {
        imgPrefix: uni.getStorageSync('imgPrefix'),
        baseimgUrl: this.$baseImgUrl,
        scrllViewRef: null,
        searchValue: '',
        inputStyles: {
          background: '#f8f8f8',
          borderRadius: '340rpx 340rpx 340rpx 340rpx',
          border: '1rpx solid #F1F2F3',
        },
        staticParams: {},
        options: {},
        halfColorButton,
        routerParams: {},
        show: false,
        data: [{}],
        innerAudioContext: null,
        showVoice: false,
        timer: null,
        countdown: 25,
        ws: null,
        listData: [],
        currentIndex: 0,
        limit: 0,
        lockReconnect: false,
        socketTimer: null,
        isOnunload: false,
        clickIndex: 0
      }
    },
    onLoad(options) {
      this.options = options
      this.routerParams = getOptionsParams(options)
      Object.assign(this.staticParams, {
        imei: this.routerParams.imei
      })
      this.$refs.scrllViewRef.getList('init', this.staticParams)
      // this.connectSocket()
      // this.connectWebSocket()
      // 开启链接
    },
    onReady() {
      this.innerAudioContext = uni.createInnerAudioContext({
        useWebAudioImplement: true
      });

      this.innerAudioContext.onPlay(() => {
        console.log('开始播放');

      });
      // 播放报错的事件监听
      this.innerAudioContext.onError((res) => {
        console.log(res)
        const item = this.listData[this.currentIndex]
        this.$set(this.listData, this.currentIndex, {
          ...item,
          play: false
        })
        console.log(this.listData)
      });
      // 播放完成
      this.innerAudioContext.onEnded((res) => {
        console.log('播放完成')
        const item = this.listData[this.currentIndex]
        this.$set(this.listData, this.currentIndex, {
          ...item,
          play: false
        })
      });
    },
    onUnload() {
      this.isOnunload = true
      uni.$off('caringAdd')
      this.innerAudioContext.stop()
      this.innerAudioContext.destroy()
      this.closeSocket()
    },
    methods: {
      moment,
      handleAddVoive() {
        this.show = true
      },
      handlePlay(item, list, index) {
        this.currentIndex = index
        this.listData = list
        // 开始自动播放
        this.innerAudioContext.autoplay = true;
        // 设置音频地址
        this.innerAudioContext.src = this.imgPrefix + item.minioUrl
        this.innerAudioContext.play()
        // this.innerAudioContext.src = 'https://www.xazhsq.cn/media/env_voice/867633060060845/20241222134418.amr';
        // this.innerAudioContext.src = 'https://web-ext-storage.dcloud.net.cn/uni-app/ForElise.mp3';
        // this.innerAudioContext.src = 'http://192.168.1.85:9000/law/pickupUrl/2025-01-08/1876865646530363394.mp3';

        // 开始播放的回调函数
        list.forEach((item, i) => {
          this.$set(list, i, {
            ...item,
            play: false
          })
        })
        setTimeout(() => {
          this.$set(list, index, {
            ...item,
            play: true
          })
        })
      },
      handlePause(item, list, index) {
        this.currentIndex = index
        this.$set(list, index, {
          ...item,
          play: false
        })
        console.log('暂停', item)
        this.innerAudioContext.pause()
      },
      startCountdown() {
        if (!this.timer) {
          this.timer = setInterval(() => {
            console.log(this.countdown)
            if (this.countdown > 0) {
              this.countdown--;
            } else {
              console.log('else')
              this.resetCountdown()
            }
          }, 1000);
        }
      },
      handleStartVoice() {
        this.show = false
        this.getEnvVoice()
      },
      getEnvVoice() {
        isLoading(true)
        const userId = uni.getStorageSync('user').id
        getAction('/web/wb/wbHttp/getEnvvoice', {
            imei: this.routerParams.imei,
            userId,
            type: 1
          })
          .then((res) => {
            if (res.code == 200) {
              this.showVoice = true
              this.startCountdown()
              // 第一次点击的时候开启
              if (this.clickIndex == 0) {
                // this.linkSocket()
                this.initWebsocket()
              }
              this.clickIndex++
            } else {}
          })
          .finally(() => {
            isLoading(false)
          })
      },
      closeSocket() {
        if (this.$websocket) {
          this.$websocket.disconnect()
        }
      },
      handleCallBack(list) {
        list.forEach((item) => {
          item.play = false
        })
      },
      resetCountdown() {
        clearInterval(this.timer);
        this.timer = null;
        // 倒计时结束关闭弹窗刷新列表
        this.showVoice = false
        this.countdown = 25
        this.$refs.scrllViewRef.getList('init', this.staticParams)
      },
      initWebsocket() {
        const userId = uni.getStorageSync('user').id
        const baseUrl = getRequestBaseUrl().replace('https://', '')
        const imei = this.routerParams.imei
        const type = 1
        const url = `wss://${baseUrl}/websocket/${userId}?imei=${imei}&type=${type}`
        this.$websocket = new WebsocketTask(url, 3000)
        // 初始化ws
        this.$websocket.initWebsocket()
        // 设置回调
        this.$websocket.setCallback((msg) => {
          // 收到消息时的回调逻辑
          let data = msg
          if (data.cmd == '远程拾音') {
            Toast('远程拾音完成！')
            this.resetCountdown()
          }
        })
      }
    },
  }
</script>

<style lang="scss" scoped>
  .root {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    background: #F9F9F9;


    .top {
      padding: 25rpx;
      background: #FFFFFF;

      /deep/ .is-input-border {
        background: #F8F8F8 !important;
        border-radius: 340rpx 340rpx 340rpx 340rpx !important;
        border: 1rpx solid #F1F2F3 !important;
      }
    }

    .bottom {
      height: 120rpx;
      background: #FFFFFF;
      border-radius: 0rpx 0rpx 0rpx 0rpx;
      flex-shrink: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 24rpx;

      /deep/.u-button__text {
        font-weight: bold;
        font-size: 32rpx;
        color: #2488F5;
      }
    }

    /deep/.u-popup {
      flex: unset;
    }

    .voice-box {
      display: flex;
      flex-direction: column;
      align-items: center;

      .vioce-img {
        width: 223rpx;
        height: 248rpx;
      }

      .tt-1 {
        font-weight: bold;
        font-size: 32rpx;
        color: #333333;
      }

      .tt-2 {
        font-weight: 400;
        font-size: 26rpx;
        color: #999999;
        margin-top: 31rpx;
        margin-bottom: 51rpx;
      }

      .tt-3 {
        font-weight: 500;
        font-size: 28rpx;
        color: #333333;
      }
    }


    .content {
      flex: 1;
      padding: 10rpx 15rpx;
      height: 0;
    }

    .care-item {
      background: #FFFFFF;
      border-radius: 8rpx 8rpx 8rpx 8rpx;
      padding: 33rpx 42rpx 26rpx 42rpx;
      margin-bottom: 10rpx;

      .item-title {
        font-weight: bold;
        font-size: 32rpx;
        color: #000000;
        margin-bottom: 30rpx;
      }

      .item-box {
        display: flex;
        justify-content: space-between;

        .s-img {
          width: 88rpx;
          height: 88rpx;
          flex-shrink: 0;
        }
      }

      .item-i {
        display: flex;
        margin-bottom: 14rpx;

        .item-label {
          font-weight: 500;
          font-size: 28rpx;
          color: #A1A1A1;
          flex-shrink: 0;
        }

        .item-value {
          font-weight: bold;
          font-size: 28rpx;
          color: #333333;
          margin-left: 16rpx;
        }

      }
    }

    .bottom {}
  }
</style>